package org.devf.fork.imsimulator.service;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import org.devf.fork.imsimulator.http.ApiClientFactory;
import org.devf.fork.imsimulator.http.pojo.ApiResult;
import org.devf.fork.imsimulator.model.DevConstant;
import org.devf.fork.imsimulator.model.HttpConstant;
import org.devf.fork.imsimulator.model.UserModel;
import org.devf.fork.imsimulator.service.dto.LoginRequest;
import org.devf.fork.imsimulator.service.vo.LoginResponse;
import org.devf.fork.imsimulator.socket.DefaultTcpClient;
import org.devf.fork.imsimulator.socket.TcpClientFactory;
import org.devf.fork.imsimulator.socket.dto.ConnectPackets;

/**
 * LoginService related
 *
 * @author wanghuafu
 * @since 0.1 2023/9/12
 */
public class LoginService{

    public LoginService() {
    }

    public LoginResponse requestLogin(String userName, String password,String deviceCode) {
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setPassword(password);
        loginRequest.setPhone(userName);
        loginRequest.setClientId(DevConstant.CLIENT_ID+deviceCode);
        String string = ApiClientFactory.getDefaultClient().execute(HttpConstant.WebUrl.LOGIN_PATH, HttpConstant.ReqMethod.POST, JSONUtil.toJsonStr(loginRequest));
        ApiResult<LoginResponse> loginResponseApiResult = JSONUtil.toBean(string, new TypeReference<>() {
        },false);
        return loginResponseApiResult.getData();
    }

    public boolean buildTcpConnect(UserModel loginUser,String token) {
        ConnectPackets packets = ConnectPackets.build(loginUser,token);
        DefaultTcpClient tcpClient = TcpClientFactory.getDefault();
        return tcpClient.getChannel().write(JSONUtil.toJsonStr(packets));
    }


}
